package xyz.archknight.app.loginput.dictionary.gen.ui

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.swing.Swing
import org.jetbrains.exposed.sql.transactions.transaction
import xyz.archknight.app.loginput.dictionary.gen.bean.DatabaseProtocol
import xyz.archknight.app.loginput.dictionary.gen.dao.Word
import xyz.archknight.app.loginput.dictionary.gen.service.EventBus
import xyz.archknight.app.loginput.dictionary.gen.ui.component.ProgressDialog
import java.io.File
import java.io.FileWriter
import java.io.IOException
import javax.swing.JFrame
import javax.swing.JOptionPane

/**
 * 将主词库内容导出为.txt文件对话框
 *
 * @author midnite
 * create at 2020-06-18 5:58 下午
 */
class ExportDialog(owner: JFrame) : ProgressDialog(owner, "正在导出词库") {
    private var lines: Int = 0

    fun export(file: String) {
        GlobalScope.launch(Dispatchers.IO) {
            try {
                val filePath = if (file.endsWith(".txt")) {
                    file
                } else {
                    "$file.txt"
                }
                val targetFile = File(filePath)
                transaction {
                    val words = Word.all()
                    lines = words.count().toInt()
                    launch(Dispatchers.Swing) {
                        progressBar.minimum = 0
                        progressBar.value = 0
                        progressBar.maximum = lines
                        progressLabel.text = "${progressBar.value} / ${progressBar.maximum}"
                    }
                    FileWriter(targetFile).use { writer ->
                        words.forEach { word ->
                            launch(Dispatchers.Swing) {
                                progressBar.value++
                                progressLabel.text = "${progressBar.value} / ${progressBar.maximum}"
                            }
                            writer.appendln("${word.phase}\t${word.pinyin}")
                        }
                    }
                }
            } catch (e: IOException) {
                JOptionPane.showMessageDialog(
                    this@ExportDialog,
                    "指定文件导出失败！",
                    "导出失败",
                    JOptionPane.ERROR_MESSAGE
                )
            }
            launch(Dispatchers.Swing) {
                isVisible = false
            }
        }
    }

}